<!DOCTYPE html>
<html lang="zh-CN" class="h-100">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI助手 - 跨境电商竞品分析系统</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.0.0/css/all.min.css">
    <style>
        :root {
            --color-primary: #2563eb;
            --color-primary-dark: #1d4ed8;
            --color-primary-light: #dbeafe;
            --color-secondary: #64748b;
            --color-success: #22c55e;
            --color-warning: #f59e0b;
            --color-error: #ef4444;
            --color-background: #f8fafc;
            --color-surface: #ffffff;
            --color-text: #1e293b;
            --color-text-light: #64748b;
            --color-border: #e2e8f0;
            --shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.05);
            --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
            --radius-sm: 0.375rem;
            --radius-md: 0.5rem;
            --radius-lg: 0.75rem;
            --font-sans: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
        }
        
        /* 基础样式 */
        html, body {
            height: 100%;
            margin: 0;
            padding: 0;
            font-family: var(--font-sans);
            background-color: var(--color-background);
            color: var(--color-text);
        }
        
        /* 布局容器 */
        .app-container {
            display: flex;
            flex-direction: column;
            height: 100vh;
            overflow: hidden;
        }
        
        .main-content {
            display: flex;
            flex: 1;
            overflow: hidden;
        }
        
        /* 侧边栏样式 */
        .sidebar {
            width: 320px;
            background-color: var(--color-surface);
            border-right: 1px solid var(--color-border);
            display: flex;
            flex-direction: column;
            transition: transform 0.3s ease;
        }
        
        .sidebar-header {
            padding: 1.25rem;
            border-bottom: 1px solid var(--color-border);
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        
        .sidebar-title {
            font-size: 1.25rem;
            font-weight: 600;
            color: var(--color-text);
            margin: 0;
        }
        
        .sidebar-content {
            flex: 1;
            overflow-y: auto;
            padding: 1rem;
        }
        
        /* 聊天区域样式 */
        .chat-container {
            flex: 1;
            display: flex;
            flex-direction: column;
            background-color: var(--color-surface);
            position: relative;
        }
        
        .chat-header {
            padding: 1rem 1.5rem;
            border-bottom: 1px solid var(--color-border);
            background-color: var(--color-surface);
            z-index: 10;
        }
        
        .chat-messages {
            flex: 1;
            overflow-y: auto;
            padding: 1.5rem;
            display: flex;
            flex-direction: column;
            gap: 1rem;
        }
        
        .message {
            display: flex;
            flex-direction: column;
            max-width: 80%;
            animation: fadeIn 0.3s ease;
        }
        
        .message-user {
            align-self: flex-end;
        }
        
        .message-assistant {
            align-self: flex-start;
        }
        
        .message-content {
            padding: 1rem;
            border-radius: var(--radius-lg);
            box-shadow: var(--shadow-sm);
            line-height: 1.5;
        }
        
        .message-user .message-content {
            background-color: var(--color-primary);
            color: white;
            border-bottom-right-radius: var(--radius-sm);
        }
        
        .message-assistant .message-content {
            background-color: var(--color-background);
            border-bottom-left-radius: var(--radius-sm);
        }
        
        .message-system {
            align-self: center;
            max-width: 600px;
            background-color: var(--color-primary-light);
            border-radius: var(--radius-lg);
            padding: 1.5rem;
            margin: 1rem 0;
            color: var(--color-primary);
            border: 1px solid rgba(37, 99, 235, 0.2);
            font-size: 0.95rem;
        }
        
        .message-system p:last-child {
            margin-bottom: 0;
        }
        
        .primary-button,
        .secondary-button {
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.5rem 1rem;
            border: none;
            border-radius: var(--radius-md);
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s;
            position: relative;
            overflow: hidden;
        }
        
        .primary-button:active,
        .secondary-button:active {
            transform: translateY(1px);
        }
        
        .primary-button::after,
        .secondary-button::after {
            content: '';
            position: absolute;
            width: 100%;
            height: 100%;
            top: 0;
            left: 0;
            background-color: rgba(255, 255, 255, 0.3);
            opacity: 0;
            border-radius: inherit;
            transition: opacity 0.2s;
        }
        
        .primary-button:active::after,
        .secondary-button:active::after {
            opacity: 1;
        }
        
        /* 输入区域样式 */
        .chat-input-container {
            padding: 1rem 1.5rem;
            background-color: var(--color-surface);
            border-top: 1px solid var(--color-border);
            position: relative;
        }
        
        .input-wrapper {
            display: flex;
            align-items: flex-end;
            gap: 0.75rem;
            background-color: var(--color-background);
            border-radius: var(--radius-lg);
            padding: 0.75rem;
            box-shadow: var(--shadow-sm);
        }
        
        .input-textarea {
            flex: 1;
            border: none;
            background: none;
            resize: none;
            min-height: 24px;
            max-height: 150px;
            padding: 0;
            font-family: inherit;
            font-size: 1rem;
            line-height: 1.5;
            color: var(--color-text);
        }
        
        .input-textarea:focus {
            outline: none;
        }
        
        .send-button {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background-color: var(--color-primary);
            color: white;
            border: none;
            cursor: pointer;
            transition: background-color 0.2s ease;
        }
        
        .send-button:hover {
            background-color: var(--color-primary-dark);
        }
        
        .send-button:disabled {
            background-color: var(--color-secondary);
            cursor: not-allowed;
        }
        
        /* 产品列表样式 */
        .product-list {
            display: flex;
            flex-direction: column;
            gap: 0.75rem;
        }
        
        .product-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0.75rem;
            border: 1px solid var(--color-border);
            border-radius: var(--radius-md);
            background-color: var(--color-surface);
            transition: all 0.2s;
            margin-bottom: 0.5rem;
        }
        
        .product-item:hover {
            border-color: var(--color-primary);
            background-color: var(--color-primary-light);
        }
        
        .product-item.selected {
            border-color: var(--color-primary);
            background-color: var(--color-primary-light);
        }
        
        .product-item .product-info {
            flex: 1;
            min-width: 0;
        }
        
        .product-item .product-name {
            font-size: 0.9rem;
            font-weight: 500;
            margin: 0;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        .product-item .product-meta {
            margin-top: 0.25rem;
            font-size: 0.8rem;
        }
        
        /* 动画效果 */
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        /* 响应式设计 */
        @media (max-width: 768px) {
            .sidebar {
                position: fixed;
                left: 0;
                top: 0;
                bottom: 0;
                z-index: 100;
                transform: translateX(-100%);
            }
            
            .sidebar.active {
                transform: translateX(0);
            }
            
            .chat-container {
                width: 100%;
            }
        }
        
        /* 工具栏样式 */
        .toolbar {
            display: flex;
            gap: 0.5rem;
            padding: 0.5rem;
            border-top: 1px solid var(--color-border);
        }
        
        .toolbar-button {
            padding: 0.5rem;
            border: none;
            background: none;
            color: var(--color-text-light);
            cursor: pointer;
            border-radius: var(--radius-sm);
            transition: all 0.2s ease;
        }
        
        .toolbar-button:hover {
            background-color: var(--color-background);
            color: var(--color-primary);
        }
        
        /* 加载状态样式 */
        .loading-spinner {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 2px solid var(--color-primary-light);
            border-radius: 50%;
            border-top-color: var(--color-primary);
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        
        .sources-section {
            margin-top: 0.5rem;
            padding: 0.5rem;
            border-top: 1px solid var(--color-border);
            font-size: 0.875rem;
        }
        
        .sources-label {
            color: var(--color-text-secondary);
            margin-bottom: 0.25rem;
            font-weight: 500;
        }
        
        .source-items {
            display: flex;
            flex-wrap: wrap;
            gap: 0.5rem;
        }
        
        .source-item {
            display: inline-block;
            padding: 0.25rem 0.5rem;
            background-color: var(--color-primary-light);
            color: var(--color-primary);
            border-radius: var(--radius-sm);
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .source-item:hover {
            background-color: var(--color-primary);
            color: white;
        }
        
        .product-list {
            display: flex;
            flex-direction: column;
            gap: 0.5rem;
            padding: 0.5rem;
        }
        
        .message-actions {
            display: flex;
            gap: 0.5rem;
            margin-top: 0.5rem;
            justify-content: flex-end;
        }
        
        .message-actions button {
            padding: 0.25rem 0.5rem;
            background: none;
            border: 1px solid var(--color-border);
            border-radius: var(--radius-sm);
            color: var(--color-text-secondary);
            font-size: 0.875rem;
            cursor: pointer;
            transition: all 0.2s;
            display: inline-flex;
            align-items: center;
            gap: 0.25rem;
        }
        
        .message-actions button:hover {
            background-color: var(--color-primary-light);
            color: var(--color-primary);
            border-color: var(--color-primary);
        }
    </style>
</head>
<body class="d-flex flex-column h-100">
    <div class="app-container">
        <nav class="navbar navbar-expand-lg navbar-light bg-white border-bottom">
            <div class="container-fluid">
                <a class="navbar-brand" href="/">跨境电商竞品分析系统</a>
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="collapse navbar-collapse" id="navbarNav">
                    <ul class="navbar-nav me-auto">
                        <li class="nav-item">
                            <a class="nav-link" href="/products">产品列表</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="/create-product">创建产品</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="/compare-products">产品对比</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active" href="/chat">AI 助手</a>
                        </li>
                    </ul>
                </div>
            </div>
        </nav>

        <div class="main-content">
            <aside class="sidebar" id="sidebar">
                <div class="sidebar-header">
                    <h3 class="sidebar-title">产品知识库</h3>
                    <button class="toolbar-button" id="sidebarToggle">
                        <i class="fas fa-bars"></i>
                    </button>
                </div>

                <div class="sidebar-content">
                    <!-- 常见问题部分 -->
                    <section class="sidebar-section">
                        <h4 class="section-title">常见问题</h4>
                        <div class="question-list">
                            <button class="question-item" onclick="askQuestion('产品的主要优势是什么？')">
                                产品的主要优势是什么？
                            </button>
                            <button class="question-item" onclick="askQuestion('产品与竞品相比如何？')">
                                产品与竞品相比如何？
                            </button>
                            <button class="question-item" onclick="askQuestion('产品的技术参数是什么？')">
                                产品的技术参数是什么？
                            </button>
                            <button class="question-item" onclick="askQuestion('产品适合哪些目标客户？')">
                                产品适合哪些目标客户？
                            </button>
                        </div>
                    </section>

                    <!-- 产品列表部分 -->
                    <section class="sidebar-section">
                        <div class="section-header">
                            <h4 class="section-title">产品列表</h4>
                            <button class="toolbar-button" onclick="refreshProducts()">
                                <i class="fas fa-sync-alt"></i>
                            </button>
                        </div>
                        
                        <div id="productListContainer" class="product-list-container">
                            <div id="productListLoading" class="loading-state" style="display: none;">
                                <div class="loading-spinner"></div>
                                <span>加载中...</span>
                            </div>
                            
                            <div id="productListEmpty" class="empty-state" style="display: none;">
                                <i class="fas fa-box-open"></i>
                                <p>暂无产品</p>
                                <button class="primary-button" onclick="window.location.href='/create-product'">
                                    <i class="fas fa-plus"></i> 创建产品
                                </button>
                            </div>
                            
                            <div id="productListError" class="error-state" style="display: none;">
                                <i class="fas fa-exclamation-circle"></i>
                                <p>加载失败</p>
                                <button class="secondary-button" onclick="refreshProducts()">
                                    <i class="fas fa-redo"></i> 重试
                                </button>
                            </div>
                            
                            <div id="productList" class="product-list"></div>
                        </div>
                    </section>

                    <!-- 文档上传部分 -->
                    <section class="sidebar-section">
                        <h4 class="section-title">文档上传</h4>
                        <div class="upload-container">
                            <label class="upload-label" for="documentFile">
                                <i class="fas fa-cloud-upload-alt"></i>
                                <span>点击或拖拽文件上传</span>
                                <small>支持 PDF、Word、TXT 格式</small>
                            </label>
                            <input type="file" id="documentFile" class="upload-input" accept=".pdf,.docx,.txt" hidden />
                            
                            <div id="uploadPreview" class="upload-preview" style="display: none;">
                                <div class="file-info">
                                    <i class="fas fa-file-alt"></i>
                                    <span id="fileName">文件名称</span>
                                </div>
                                <button class="primary-button" id="uploadButton" onclick="uploadDocument()">
                                    <i class="fas fa-upload"></i> 上传
                                </button>
                            </div>
                        </div>
                    </section>
                </div>
            </aside>

            <main class="chat-container">
                <header class="chat-header">
                    <h2>产品专家 AI 助手</h2>
                </header>

                <div class="chat-messages" id="chatMessages">
                    <div class="message message-system">
                        <div class="message-content">
                            <p>您好，我是产品专家 AI 助手。我可以帮助您：</p>
                            <ul>
                                <li>分析产品特点和优势</li>
                                <li>对比不同产品的差异</li>
                                <li>回答产品相关问题</li>
                                <li>提供市场洞察建议</li>
                            </ul>
                            <p><strong>提示：</strong>从侧边栏选择一个或多个产品，我可以基于这些产品的数据为您提供更具体的分析。</p>
                        </div>
                    </div>
                </div>

                <div class="chat-input-container">
                    <div class="selected-products" id="selectedProducts"></div>
                    <div class="input-wrapper">
                        <textarea 
                            id="userInput" 
                            class="input-textarea" 
                            placeholder="输入您的问题..."
                            rows="1"
                            onInput="this.style.height = 'auto'; this.style.height = this.scrollHeight + 'px'"
                        ></textarea>
                        <button id="sendButton" class="send-button" disabled>
                            <i class="fas fa-paper-plane"></i>
                        </button>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <script>
        let selectedProducts = [];
        let isAiTyping = false;
        let systemInitialized = false;
        let lastUserMessage = '';
        
        const chatMessages = document.getElementById('chatMessages');
        const userInput = document.getElementById('userInput');
        const sendButton = document.getElementById('sendButton');
        
        document.addEventListener('DOMContentLoaded', function() {
            checkSystemStatus();
            loadProducts();
            initChatInput();
            initSidebar();
            initFileUpload();
            
            setTimeout(() => {
                userInput.focus();
            }, 500);
        });

        function initChatInput() {
            userInput.addEventListener('keydown', function(e) {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    sendMessage();
                }
            });
            
            userInput.addEventListener('input', function() {
                sendButton.disabled = this.value.trim().length === 0;
                this.style.height = 'auto';
                this.style.height = Math.min(150, this.scrollHeight) + 'px';
            });
            
            sendButton.addEventListener('click', sendMessage);
        }

        function initSidebar() {
            const sidebarToggle = document.getElementById('sidebarToggle');
            const sidebar = document.getElementById('sidebar');
            
            if (sidebarToggle) {
                sidebarToggle.addEventListener('click', () => {
                    sidebar.classList.toggle('collapsed');
                });
            }
        }

        function initFileUpload() {
            const fileInput = document.getElementById('documentFile');
            const uploadPreview = document.getElementById('uploadPreview');
            const fileName = document.getElementById('fileName');
            
            fileInput.addEventListener('change', function(e) {
                const file = e.target.files[0];
                if (file) {
                    fileName.textContent = file.name;
                    uploadPreview.style.display = 'flex';
                }
            });
        }

        function refreshProducts() {
            // 添加系统消息
            addMessage("正在刷新产品列表...", "system");
            
            // 清空当前选择
            if (selectedProducts.length > 0) {
                selectedProducts = [];
                updateSelectedProducts();
            }
            
            // 加载产品
            loadProducts().then(success => {
                if (success) {
                    addMessage("产品列表已更新，您可以选择产品进行分析。", "system");
                } else {
                    addMessage("产品列表更新失败，请检查网络连接或联系管理员。", "error");
                }
            });
        }

        async function loadProducts() {
            if (window.isProductsLoading) return false;
            
            window.isProductsLoading = true;
            const productListContainer = document.getElementById('productListContainer');
            const loading = document.getElementById('productListLoading');
            const empty = document.getElementById('productListEmpty');
            const error = document.getElementById('productListError');
            const list = document.getElementById('productList');
            
            loading.style.display = 'block';
            empty.style.display = 'none';
            error.style.display = 'none';
            list.style.display = 'none';
            
            console.log('正在加载产品列表...');
            
            try {
                // 尝试不同的API路径
                const apiPaths = ['/api/products/static', '/api/products', '/api/products/products'];
                let products = null;
                let success = false;
                
                for (const path of apiPaths) {
                    try {
                        console.log(`尝试从 ${path} 获取产品`);
                        const response = await fetch(path);
                        
                        if (!response.ok) {
                            console.warn(`${path} 返回状态码: ${response.status}`);
                            continue;
                        }
                        
                        const data = await response.json();
                        console.log(`${path} 返回数据:`, data);
                        
                        // 处理不同的返回格式
                        if (Array.isArray(data)) {
                            products = data;
                        } else if (data && typeof data === 'object') {
                            if (Array.isArray(data.products)) {
                                products = data.products;
                            } else if (Object.keys(data).length > 0) {
                                // 假设是对象列表
                                products = Object.values(data);
                            }
                        }
                        
                        if (products && products.length > 0) {
                            success = true;
                            break;
                        }
                    } catch (err) {
                        console.error(`从 ${path} 获取产品失败:`, err);
                    }
                }
                
                loading.style.display = 'none';
                
                if (!success || !products || products.length === 0) {
                    console.warn('没有找到产品');
                    empty.style.display = 'block';
                    return false;
                }
                
                console.log(`找到 ${products.length} 个产品`, products);
                list.innerHTML = '';
                list.style.display = 'block';
                
                products.forEach(product => {
                    const productId = product.id || product._id || Object.keys(product)[0];
                    const productName = product.name || (productId ? productId.split('_')[0] : '未命名产品');
                    const isAnalyzed = product.is_analyzed || product.analyzed || false;
                    
                    const item = document.createElement('div');
                    item.className = 'product-item';
                    item.dataset.id = productId;
                    item.innerHTML = `
                        <div class="product-info">
                            <h5 class="product-name">${productName}</h5>
                            <div class="product-meta">
                                ${isAnalyzed ? '<span class="badge bg-success">已分析</span>' : ''}
                            </div>
                        </div>
                        <button class="secondary-button" onclick="selectProduct('${productId}')">
                            选择
                        </button>
                    `;
                    list.appendChild(item);
                });
                
                // 更新产品按钮状态
                updateProductButtons();
                return true;
                
            } catch (err) {
                console.error('加载产品失败:', err);
                loading.style.display = 'none';
                error.style.display = 'block';
                return false;
            } finally {
                window.isProductsLoading = false;
            }
        }

        function selectProduct(productId) {
            if (!productId) return;
            
            // 检查产品是否已经被选择
            const index = selectedProducts.indexOf(productId);
            
            if (index !== -1) {
                // 取消选择
                selectedProducts.splice(index, 1);
                console.log(`取消选择产品: ${productId}`);
                
                // 添加系统消息提示用户
                if (selectedProducts.length === 0) {
                    addMessage("您已取消所有产品选择。继续提问将基于通用知识回答。", "system");
                } else {
                    const remainingNames = selectedProducts.map(id => id.split('_')[0]).join(', ');
                    addMessage(`您已取消选择一个产品。当前选择的产品: ${remainingNames}`, "system");
                }
            } else {
                // 新选择一个产品
                selectedProducts.push(productId);
                console.log(`选择产品: ${productId}`);
                
                // 产品名称
                const productName = productId.split('_')[0];
                
                // 添加系统消息提示用户
                if (selectedProducts.length === 1) {
                    addMessage(`您已选择产品: ${productName}。接下来的问题我将基于此产品的数据回答。`, "system");
                } else {
                    const allNames = selectedProducts.map(id => id.split('_')[0]).join(', ');
                    addMessage(`您已增加选择产品: ${productName}。当前选择的产品: ${allNames}`, "system");
                }
            }
            
            // 更新UI
            updateSelectedProducts();
            updateProductButtons();
        }

        function updateSelectedProducts() {
            const container = document.getElementById('selectedProducts');
            container.innerHTML = '';
            
            selectedProducts.forEach(productId => {
                const tag = document.createElement('div');
                tag.className = 'selected-product';
                tag.innerHTML = `
                    <span>${productId.split('_')[0]}</span>
                    <button onclick="selectProduct('${productId}')">
                        <i class="fas fa-times"></i>
                    </button>
                `;
                container.appendChild(tag);
            });
        }

        function updateProductButtons() {
            document.querySelectorAll('.product-item').forEach(item => {
                const button = item.querySelector('button');
                const productId = button.getAttribute('onclick').match(/'([^']+)'/)[1];
                
                if (selectedProducts.includes(productId)) {
                    button.classList.add('primary-button');
                    button.classList.remove('secondary-button');
                } else {
                    button.classList.add('secondary-button');
                    button.classList.remove('primary-button');
                }
            });
        }

        async function sendMessage() {
            const message = userInput.value.trim();
            if (!message || isAiTyping) return;
            
            lastUserMessage = message;
            
            // 获取选中的产品名称用于显示
            let productContext = '';
            if (selectedProducts.length > 0) {
                const productNames = selectedProducts.map(id => id.split('_')[0]);
                productContext = `[基于产品: ${productNames.join(', ')}] `;
            }
            
            // 添加用户消息，可能包含产品上下文
            addMessage(`${productContext}${message}`, 'user');
            
            userInput.value = '';
            userInput.style.height = 'auto';
            sendButton.disabled = true;
            
            showTypingIndicator();
            
            try {
                // 构建请求体，包含产品IDs
                const requestBody = {
                    question: message,
                    max_tokens: 2048
                };
                
                if (selectedProducts.length > 0) {
                    requestBody.product_ids = selectedProducts;
                    console.log('使用产品进行分析:', selectedProducts);
                }
                
                const response = await fetch('/api/ai/ask', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(requestBody)
                });
                
                if (!response.ok) throw new Error('发送消息失败');
                
                const result = await response.json();
                removeTypingIndicator();
                
                if (result.status === 'error') {
                    systemInitialized = false;
                    addMessage(result.message || '处理消息时出错', 'error');
                    return;
                }
                
                addMessage(result.answer, 'assistant', result.sources || []);
                
            } catch (error) {
                console.error('发送消息失败:', error);
                removeTypingIndicator();
                addMessage('抱歉，处理您的问题时出现错误。请稍后再试。', 'error');
            }
        }

        function showTypingIndicator() {
            isAiTyping = true;
            if (document.getElementById('typingIndicator')) return;
            
            const indicator = document.createElement('div');
            indicator.className = 'message message-assistant';
            indicator.id = 'typingIndicator';
            indicator.innerHTML = `
                <div class="message-content">
                    <div class="loading-spinner"></div>
                    <span>AI正在思考...</span>
                </div>
            `;
            
            chatMessages.appendChild(indicator);
            scrollToBottom();
        }

        function removeTypingIndicator() {
            isAiTyping = false;
            const indicator = document.getElementById('typingIndicator');
            if (indicator) indicator.remove();
        }

        function addMessage(text, sender, sources = []) {
            const message = document.createElement('div');
            message.className = `message message-${sender}`;
            
            const content = document.createElement('div');
            content.className = 'message-content';
            content.innerHTML = marked.parse(text);
            
            message.appendChild(content);
            
            if (sender === 'assistant' || sender === 'error') {
                const actions = document.createElement('div');
                actions.className = 'message-actions';
                actions.innerHTML = `
                    <button onclick="copyMessage(this)">
                        <i class="fas fa-copy"></i> 复制
                    </button>
                    ${sender === 'error' && lastUserMessage ? `
                        <button onclick="retryMessage()">
                            <i class="fas fa-redo"></i> 重试
                        </button>
                    ` : ''}
                `;
                message.appendChild(actions);
                
                if (sources && sources.length > 0) {
                    addSourcesSection(message, sources);
                }
            }
            
            chatMessages.appendChild(message);
            scrollToBottom();
        }

        function addSourcesSection(messageDiv, sources) {
            if (!sources || sources.length === 0) return;
            
            const sourcesDiv = document.createElement('div');
            sourcesDiv.className = 'sources-section';
            sourcesDiv.innerHTML = '<div class="sources-label">信息来源:</div>';
            
            const sourcesList = document.createElement('div');
            sourcesList.className = 'source-items';
            
            sources.forEach((source, index) => {
                const sourceItem = document.createElement('span');
                sourceItem.className = 'source-item';
                sourceItem.textContent = source.metadata?.title || `来源 ${index + 1}`;
                sourceItem.onclick = () => showSourceDetails(source);
                sourcesList.appendChild(sourceItem);
            });
            
            sourcesDiv.appendChild(sourcesList);
            messageDiv.appendChild(sourcesDiv);
        }

        function showSourceDetails(source) {
            const modal = document.createElement('div');
            modal.className = 'modal fade show';
            modal.style.display = 'block';
            modal.innerHTML = `
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">来源详情</h5>
                            <button type="button" class="btn-close" onclick="this.closest('.modal').remove()"></button>
                        </div>
                        <div class="modal-body">
                            <pre>${source.content || source.page_content || '无内容'}</pre>
                        </div>
                    </div>
                </div>
            `;
            document.body.appendChild(modal);
        }

        function copyMessage(button) {
            const text = button.closest('.message').querySelector('.message-content').textContent;
            navigator.clipboard.writeText(text).then(() => {
                button.innerHTML = '<i class="fas fa-check"></i> 已复制';
                setTimeout(() => {
                    button.innerHTML = '<i class="fas fa-copy"></i> 复制';
                }, 2000);
            });
        }

        function retryMessage() {
            if (lastUserMessage) {
                userInput.value = lastUserMessage;
                sendMessage();
            }
        }

        function askQuestion(question) {
            if (!isAiTyping) {
                userInput.value = question;
                sendMessage();
            }
        }

        async function uploadDocument() {
            const fileInput = document.getElementById('documentFile');
            const file = fileInput.files[0];
            if (!file) return;
            
            const formData = new FormData();
            formData.append('file', file);
            
            try {
                const response = await fetch('/api/documents/upload', {
                    method: 'POST',
                    body: formData
                });
                
                if (!response.ok) throw new Error('上传失败');
                
                const result = await response.json();
                addMessage(`文档 "${file.name}" 上传成功！`, 'system');
                
                fileInput.value = '';
                document.getElementById('uploadPreview').style.display = 'none';
                
            } catch (error) {
                console.error('上传文档失败:', error);
                addMessage('抱歉，上传文档失败。请稍后重试。', 'error');
            }
        }

        async function checkSystemStatus() {
            if (window.isCheckingStatus) return;
            
            window.isCheckingStatus = true;
            console.log('检查系统状态...');
            
            try {
                const response = await fetch('/api/ai/vectors/initialize', {
                    method: 'POST'
                });
                
                if (!response.ok) throw new Error('初始化失败');
                
                const result = await response.json();
                
                if (result.status === 'success') {
                    systemInitialized = true;
                    console.log('系统已就绪');
                } else {
                    systemInitialized = false;
                    console.warn('系统未就绪:', result.message);
                    if (result.message?.includes('Could not import chromadb')) {
                        addMessage('系统检测到缺少必要依赖，AI助手功能暂时无法使用。请联系管理员安装所需依赖。', 'system');
                    }
                }
            } catch (error) {
                console.error('检查系统状态失败:', error);
                systemInitialized = false;
            } finally {
                window.isCheckingStatus = false;
            }
        }

        function scrollToBottom() {
            chatMessages.scrollTo({
                top: chatMessages.scrollHeight,
                behavior: 'smooth'
            });
        }
    </script>
</body>
</html>